package com.example.demo.dao;

import com.example.demo.config.error.BizException;
import com.example.demo.entity.Flow;
import com.example.demo.entity.Patient;
import com.example.demo.mapper.PatientMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Author: WinstonDeng
 * @Description:
 * @Date: Created in 8:16 2020/4/9
 * @Modified by:
 */
@Repository
public class PatientDao {
    @Autowired
    private PatientMapper patientMapper;

    @Autowired
    private FlowDao flowDao;

    public Patient getByOpenIdFirst(String openId, String nickName, Integer gender) throws BizException {
        Patient patient = patientMapper.findByOpenId(openId);
        // not found, then return new one
        if (patient == null){
            Patient patient_new = new Patient();
            patient_new.setOpenId(openId);
            patient_new.setNickName(nickName);
            String gender_str = "";
            if (gender == 0){
                gender_str = "未知";
            }else if(gender == 1){
                gender_str = "男";
            }else if(gender == 2){
                gender_str = "女";
            }
            patient_new.setGender(gender_str);
            patient_new.setBedNum(Patient.BEDNUM_DEFAULT);
            patient_new.setHospNum(Patient.HOSPNUM_DEFAULT);
            if(patientMapper.insertPatient(patient_new)){
                return patientMapper.findByOpenId(openId);
            } else {
              throw new BizException("500", "insert Patient error");
            }
        }else {
            List<Flow> flowList = flowDao.getListByPatientIdAndState(patient.getId(), Flow.STATE_DOING);
            for(Flow flow:flowList){
                patient.setHospNum(flow.getHospNum());
                patient.setBedNum(flow.getBedNum());
                break;
            }
            return patient;
        }
    }

    public Patient getByOpenId(String openId) throws BizException{
        Patient patient = patientMapper.findByOpenId(openId);
        List<Flow> flowList = flowDao.getListByPatientIdAndState(patient.getId(), Flow.STATE_DOING);
        for(Flow flow:flowList){
            patient.setHospNum(flow.getHospNum());
            patient.setBedNum(flow.getBedNum());
            break;
        }
        return patient;
    }

    public Patient updatePatient(Patient patient) throws BizException{
        if(!patientMapper.updatePatient(patient)){
            throw new BizException("500", "update error");
        }
        return patientMapper.findByOpenId(patient.getOpenId());
    }

    public Patient getById(long id) throws BizException{
        return patientMapper.findById(id);
    }
}
